import { ref, reactive, onMounted, h, toRaw } from "vue";
import { taskTypeApi } from "@/api/task";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import { usePublicHooks } from "@/views/system/hooks";
import editForm from "../form.vue";

export function useTaskTypes(tableRef) {
  const form = reactive({
    name: "",
    priority: "",
    feedback_type: "",
    page: 1,
    limit: 15
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const { tagStyle } = usePublicHooks();

  const pagination = reactive({
    total: 0,
    pageSize: 15,
    pageSizes: [10, 20, 40, 60, 100, 200],
    currentPage: 1,
    background: true
  });

  const columns = ref([
    { label: "勾选列", type: "selection", width: 50, fixed: true },
    { 
      label: "类型ID", 
      prop: "id", 
      width: 80, 
      align: "center",
      fixed: true
    },
    { 
      label: "任务名称", 
      prop: "name", 
      width: 150,
      showOverflowTooltip: true
    },
    { 
      label: "任务描述", 
      prop: "content", 
      minWidth: 200,
      showOverflowTooltip: true
    },
    { 
      label: "优先级", 
      prop: "priority", 
      width: 100,
      align: "center",
      cellRenderer: ({ row }) => {
        const priorityMap = {
          1: { type: "info", text: "低" },
          2: { type: "warning", text: "中" },
          3: { type: "danger", text: "高" },
          4: { type: "danger", text: "紧急" }
        };
        const priority = priorityMap[row.priority] || { type: "info", text: "未知" };
        return h("el-tag", {
          type: priority.type,
          size: "small",
          style: tagStyle.value(row.priority > 2 ? 1 : 0)
        }, priority.text);
      }
    },
    { 
      label: "期限(小时)", 
      prop: "deadline_hours", 
      width: 100,
      align: "center"
    },
    { 
      label: "反馈类型", 
      prop: "feedback_type", 
      width: 140,
      align: "center",
      cellRenderer: ({ row }) => {
        // 解析反馈类型数据
        let feedbackTypes = [];
        if (row.feedback_type) {
          try {
            feedbackTypes = Array.isArray(row.feedback_type) 
              ? row.feedback_type 
              : JSON.parse(row.feedback_type);
          } catch {
            feedbackTypes = typeof row.feedback_type === 'string' 
              ? row.feedback_type.split(',').map(t => t.trim()).filter(Boolean)
              : [row.feedback_type];
          }
        }

        const typeMap = {
          text: { type: "info", text: "文本" },
          image: { type: "success", text: "图片" }
        };

        // 渲染多个标签
        return h("div", { style: "display: flex; flex-wrap: wrap; gap: 4px; justify-content: center;" }, 
          feedbackTypes.map(type => {
            const feedback = typeMap[type] || { type: "warning", text: type };
            return h("el-tag", {
              key: type,
              type: feedback.type,
              size: "small",
              style: tagStyle.value(feedback.type === 'success' ? 1 : 0)
            }, feedback.text);
          })
        );
      }
    },
    { 
      label: "创建时间", 
      prop: "created_at", 
      width: 160,
      sortable: "custom"
    },
    { 
      label: "操作", 
      fixed: "right", 
      width: 160, 
      slot: "operation" as const
    }
  ] as any);

  function resetForm(formEl?) {
    if (formEl) {
      formEl.resetFields();
    } else {
      Object.assign(form, {
        name: "",
        priority: "",
        feedback_type: "",
        page: 1,
        limit: 15
      });
    }
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    try {
      const params = {
        ...toRaw(form),
        page: pagination.currentPage,
        limit: pagination.pageSize
      };
      
      const { data } = await taskTypeApi.list(params);
      dataList.value = data.data || [];
      pagination.total = data.total || 0;
    } catch (error) {
      console.error("获取任务类型列表失败:", error);
      message("获取数据失败", { type: "error" });
    } finally {
      loading.value = false;
    }
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(selection) {
    selectedNum.value = selection.length;
  }

  function onSelectionCancel() {
    tableRef.value.getTableRef().clearSelection();
    selectedNum.value = 0;
  }

  function chores(curData, res, title, done) {
    try {
      if (res.success) {
        message(`${title}任务类型"${curData.name}"成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        onSearch(); // 刷新表格数据
      } else {
        // 显示服务端返回的错误信息
        const errorMsg = (res as any).message || `${title}任务类型失败`;
        message(errorMsg, { type: "error" });
      }
    } catch (error) {
      message(`${title}失败`, {
        type: "error"
      });
    }
  }

  function openDialog(title = "新增", row?) {
    // 处理反馈类型数据格式
    let feedbackTypes = ["text"]; // 默认值
    if (row?.feedback_type) {
      if (Array.isArray(row.feedback_type)) {
        feedbackTypes = row.feedback_type;
      } else if (typeof row.feedback_type === 'string') {
        try {
          // 尝试解析JSON字符串
          feedbackTypes = JSON.parse(row.feedback_type);
        } catch {
          // 如果解析失败，按逗号分割
          feedbackTypes = row.feedback_type.split(',').map(t => t.trim()).filter(Boolean);
        }
      }
    }

    addDialog({
      title: `${title}任务类型`,
      props: {
        formInline: {
          name: row?.name ?? "",
          content: row?.content ?? "",
          priority: row?.priority ?? 1,
          deadline_hours: row?.deadline_hours ?? 24,
          feedback_type: feedbackTypes
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;

        FormRef.validate(valid => {
          if (valid) {
            // 验证反馈类型
            if (!curData.feedback_type || curData.feedback_type.length === 0) {
              message("请至少选择一种反馈类型", { type: "warning" });
              return;
            }

            // 提取需要提交的数据
            const submitData = {
              name: curData.name,
              content: curData.content,
              priority: curData.priority,
              deadline_hours: curData.deadline_hours,
              feedback_type: JSON.stringify(curData.feedback_type) // 转为JSON字符串存储
            };

            if (title === "新增") {
              taskTypeApi.create(submitData).then(res => chores(curData, res, title, done));
            } else {
              taskTypeApi.update(row.id, submitData).then(res => chores(curData, res, title, done));
            }
          }
        });
      }
    });
  }

  function handleEdit(row) {
    openDialog("编辑", row);
  }

  async function handleDelete(row?) {
    if (row) {
      // 删除单个 - 由于模板中已有 el-popconfirm，这里直接执行删除
      try {
        await taskTypeApi.delete(row.id);
        message(`删除任务类型"${row.name}"成功`, { type: "success" });
        onSearch();
      } catch (error) {
        console.error("删除任务类型失败:", error);
        message("删除任务类型失败", { type: "error" });
      }
    } else {
      // 批量删除
      const selection = tableRef.value.getTableRef().getSelectionRows();
      if (selection.length === 0) {
        message("请先选择要删除的数据", { type: "warning" });
        return;
      }

      try {
        const result = await ElMessageBox.confirm(
          `确认要删除选中的 ${selection.length} 条数据吗？`,
          "批量删除确认",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        );

        if (result === "confirm") {
          for (const item of selection) {
            await taskTypeApi.delete(item.id);
          }
          message("批量删除成功", { type: "success" });
          onSearch();
          onSelectionCancel();
        }
      } catch (error) {
        console.log("用户取消删除");
      }
    }
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    dataList,
    loading,
    columns,
    selectedNum,
    pagination,
    resetForm,
    onSearch,
    openDialog,
    handleEdit,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onSelectionCancel
  };
} 